<template>
  <div class="flex flex-col h-full p-4 gap-4">
    <!-- 个人信息展示区块 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h2 class="text-lg font-medium mb-4 pb-4">{{ t('profile.title.personalInfo') }}</h2>
      <div class="flex flex-col gap-4">
        <div class="flex items-center">
          <span class="text-gray-500 w-40">{{ t('profile.label.username') }}</span>
          <span>{{ userInfo.username }}</span>
          <el-button
            type="primary"
            link
            class="ml-2"
            @click="openEditUsernameDialog"
          >
            <el-icon><Edit /></el-icon>
          </el-button>
        </div>
        <div class="flex items-center">
          <span class="text-gray-500 w-40">{{ t('profile.label.roleName') }}</span>
          <span>{{ userInfo.roleName }}</span>
        </div>
        <div class="flex items-center">
          <span class="text-gray-500 w-40">{{ t('profile.label.email') }}</span>
          <span>{{ userInfo.email }}</span>
        </div>
        <div class="flex items-center">
          <span class="text-gray-500 w-40">{{ t('profile.label.phoneNumber') }}</span>
          <span>{{ userInfo.phoneNumber }}</span>
        </div>
      </div>
    </div>

    <!-- 安全设置区块 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h2 class="text-lg font-medium mb-4 pb-4">{{ t('profile.title.securitySetting') }}</h2>
      <div class="flex flex-col gap-4">
        <div class="flex items-center">
          <span class="text-gray-500 w-40">{{ t('profile.label.passwordLastReset') }}</span>
          <span>{{ security.passwordLastReset }}</span>
        </div>
        <div class="flex items-center">
          <!-- <span class="text-gray-500 w-40"></span> -->
          <el-button
            type="primary"
            link
            class="text-blue-500"
            @click="openChangePasswordDialog"
            >{{ t('profile.action.changePassword') }}</el-button
          >
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="passwordDialogVisible"
      :title="t('profile.title.changePassword')"
      width="500px"
    >
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="165px"
      >
        <el-form-item :label="t('profile.label.currentPassword')" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            :placeholder="t('profile.placeholder.enterCurrentPassword')"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item :label="t('profile.label.newPassword')" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            :placeholder="t('profile.placeholder.enterNewPassword')"
            size="large"
            show-password
          />
          <div class="text-gray-400 mt-1 text-sm">
            {{ t('profile.hint.passwordFormat') }}
          </div>
        </el-form-item>
        <el-form-item :label="t('profile.label.confirmPassword')" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            :placeholder="t('profile.placeholder.enterPasswordAgain')"
            size="large"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">{{ t('profile.common.cancel') }}</el-button>
          <el-button type="primary" @click="submitPasswordForm">
            {{ t('profile.common.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户名弹窗 -->
    <el-dialog
      v-model="usernameDialogVisible"
      :title="t('profile.title.editUsername')"
      width="500px"
    >
      <el-form
        :model="usernameForm"
        :rules="usernameRules"
        ref="usernameFormRef"
        label-width="100px"
      >
        <el-form-item :label="t('profile.label.usernameOnly')" prop="username">
          <el-input
            show-limit
            :maxlength="10"
            v-model="usernameForm.username"
            :placeholder="t('profile.placeholder.enterUsername')"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="usernameDialogVisible = false">{{ t('profile.common.cancel') }}</el-button>
          <el-button type="primary" @click="submitUsernameForm">
            {{ t('profile.common.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
// ================================
// 个人账户（Profile）页面脚本逻辑
// - 负责：展示与编辑当前登录用户的基础信息
// - 主要能力：查看个人信息、修改密码、修改用户名
// - 交互说明：
//   1) 页面挂载时优先请求后端获取个人信息；若失败则回退到全局 store 数据
//   2) 点击“Change password”打开密码弹窗，表单校验通过后提交
//   3) 点击用户名后的“笔”图标打开用户名弹窗，校验通过后提交并回填
// ================================
import { ref, reactive, onMounted, onActivated } from "vue";
import { Edit } from "@element-plus/icons-vue";
import { useAppStore } from "@/store";
import { ElMessage } from "element-plus";
import { accountSelfApi } from "@/api/business";
import type { FormInstance, FormRules } from "element-plus";
// 使用 Element Plus 自带图标，保证可用
import { useI18n } from "@/composables/useI18n";

// 1) 拿到全局应用 store：当后端接口不可用时，用于兜底读取用户信息
const appStore = useAppStore();
const { t } = useI18n();

// 2) 用户信息（展示区）：响应式对象，统一承载页面展示所需的基础字段
//    - 首选来源：accountSelfApi.getInfo()
//    - 失败回退：appStore.state.user
const userInfo = reactive({
  username: "",
  roleName: "",
  email: "",
  phoneNumber: ""
});

// 3) 安全设置数据（展示最近一次密码重置时间等）
const security = reactive({
  passwordLastReset: ""
});

// 4) 修改密码弹窗：显隐开关 + 表单引用 + 表单模型
const passwordDialogVisible = ref(false);
const passwordFormRef = ref<FormInstance>();
const passwordForm = reactive({
  currentPassword: "",
  newPassword: "",
  confirmPassword: ""
});

// 4.1) 自定义表单校验：二次确认密码与新密码一致性
// @param value: 当前输入的确认密码
// @effect: 与 newPassword 不一致时给出错误提示
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("Please enter confirm password"));
  } else if (value !== passwordForm.newPassword) {
    callback(new Error("Two inputs don't match!"));
  } else {
    callback();
  }
};

// 4.2) 自定义表单校验：当前密码必填 + 基础格式约束
// 说明：这里做了最基础的前端校验，实际强校验应交由后端完成
const validateCurrentPassword = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("Please enter password"));
  } else if (value.length < 8) {
    callback(new Error("Password must be at least 8 characters"));
  } else if (!/[A-Za-z]/.test(value)) {
    callback(new Error("Password must include at least one letter"));
  } else if (!/\d/.test(value)) {
    callback(new Error("Password must include at least one number"));
  } else if (/\s/.test(value)) {
    callback(new Error("Password must not have spaces"));
  } else {
    callback();
  }
};

// 4.3) 自定义表单校验：新密码格式（长度区间、字符类型、不含空格）
const validatePasswordFormat = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("Please enter password"));
  } else if (value.length < 8 || value.length > 32) {
    callback(new Error("Password must be at least 8 characters"));
  } else if (!/[A-Za-z]/.test(value)) {
    callback(new Error("Password must include at least one letter"));
  } else if (!/\d/.test(value)) {
    callback(new Error("Password must include at least one number"));
  } else if (/\s/.test(value)) {
    callback(new Error("Password must not have spaces"));
  } else {
    callback();
  }
};

// 4.4) 修改密码表单校验规则集合
const passwordRules = reactive<FormRules>({
  currentPassword: [{ validator: validateCurrentPassword, trigger: "blur" }],
  newPassword: [{ validator: validatePasswordFormat, trigger: "blur" }],
  confirmPassword: [
    {
      required: true,
      message: "Please enter confirm password",
      trigger: "blur"
    },
    { validator: validateConfirmPassword, trigger: "blur" }
  ]
});

// 5) 修改用户名弹窗：显隐开关 + 表单引用 + 表单模型
const usernameDialogVisible = ref(false);
const usernameFormRef = ref<FormInstance>();
const usernameForm = reactive({
  username: ""
});

// 5.1) 修改用户名表单规则：必填 + 长度约束
const usernameRules = reactive<FormRules>({
  username: [
    { required: true, message: "Please enter username", trigger: "blur" },
    {
      min: 3,
      message:
        "Length should be at least 3 characters and less than 10 characters",
      trigger: "blur"
    }
  ]
});

// 6) 弹窗显隐方法：打开“修改密码”
const openChangePasswordDialog = () => {
  passwordForm.currentPassword = "";
  passwordForm.newPassword = "";
  passwordForm.confirmPassword = "";
  passwordDialogVisible.value = true;
};

// 6.1) 弹窗显隐方法：打开“编辑用户名”（预填当前用户名）
const openEditUsernameDialog = () => {
  usernameForm.username = userInfo.username;
  usernameDialogVisible.value = true;
};

// 7) 提交密码修改
// 流程：
//   a. 触发表单校验（异步）
//   b. 通过后调用 accountSelfApi.updatePassword
//   c. 成功提示并关闭弹窗；失败交由 http 拦截/业务处理
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return;

  const valid = await passwordFormRef.value.validate();
  if (valid) {
    console.log('[Profile] updatePassword submit:', {
      current: '***',
      new: '***'
    });
    await accountSelfApi.updatePassword({
      password: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    });
    console.log('[Profile] updatePassword done');
    ElMessage.success(t('profile.message.passwordChanged'));
    passwordDialogVisible.value = false;
  } else {
    ElMessage.error(t('profile.message.fixFormErrors'));
  }
};

// 8) 提交用户名修改
// 流程：
//   a. 表单校验
//   b. 请求后端更新
//   c. 本地展示数据回填 + 成功提示 + 关闭弹窗
const submitUsernameForm = async () => {
  if (!usernameFormRef.value) return;

  const valid = await usernameFormRef.value.validate();
  if (valid) {
    console.log('[Profile] updateUsername submit:', usernameForm.username);
    await accountSelfApi.updateUsername({ username: usernameForm.username });
    userInfo.username = usernameForm.username;
    console.log('[Profile] updateUsername done');
    ElMessage.success(t('profile.message.usernameUpdated'));
    usernameDialogVisible.value = false;
  } else {
    ElMessage.error(t('profile.message.fixFormErrors'));
  }
};

// 9) 入口方法：供模板按钮直接调用，等价于打开修改密码弹窗
const changePassword = () => {
  openChangePasswordDialog();
};

// 10) 页面挂载时加载数据
// 逻辑：
//   - 优先请求 accountSelfApi.getInfo() 获取最新用户信息
//   - 若失败（网络/权限/后端不可用），回退使用 store 中已有的用户信息
onMounted(async () => {
  //  console.error('Profile mounted');
  console.log('[Profile] onMounted start');
  console.log("343:", accountSelfApi.getInfo());
  
  try {
    const info: any = await accountSelfApi.getInfo();
    console.log('[Profile] getInfo resp:', info);
    if (info && info.code === 0) {
      const d = info.data || {};
      console.log('[Profile] mapped from resp:', d);
      userInfo.username = d.username || "";
      userInfo.roleName = d.role || "";
      userInfo.email = d.email || "";
      userInfo.phoneNumber = d.mobile || "";
      security.passwordLastReset = d.modifyTime || "";
    } else {
      console.warn('[Profile] getInfo non-zero, fallback to store. code/msg:', info?.code, info?.msg);
      const u: any = appStore.state.user || {};
      console.log('[Profile] store user:', u);
      userInfo.username = u.username || "";
      userInfo.roleName = u.role || "";
      userInfo.email = u.email || "";
      userInfo.phoneNumber = u.mobile || "";
    }
  } catch (e) {
    console.error('[Profile] getInfo error:', e);
    const u: any = appStore.state.user || {};
    console.log('[Profile] store user (error fallback):', u);
    userInfo.username = u.username || "";
    userInfo.roleName = u.role || "";
    userInfo.email = u.email || "";
    userInfo.phoneNumber = u.mobile || "";
  }
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item__error) {
  color: #f56c6c;
  font-size: 14px;
  line-height: 1.5;
}
</style>
